<?php
namespace Home\Controller;
use Common\Controller\HomebaseController;
use Home\Service\ClockTimeService;
use Home\Service\WechatService;
use Home\Service\AccountService;
// +----------------------------------------------------------------------
// | Date:2017年2月17日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
class IndexController extends HomebaseController{
    public function index(){
        if ($this->approver) {
           $unread = D('Approver')->count_msg_unread($this->user_sn);
            $this->assign('unread',$unread);
        }
        
        if (strstr($this->userInfo['privilege'], '3') == '3'){
            //特权3，显示高管行程
            $this->assign('privilege_3',true);
        }
        
        $this->assign('leader',$this->_check_leader());
        $this->assign('approver',$this->approver);
        $this->display();
    }
    
    
    
    /**
     * 检查是否是主管身份，用来开启团队按钮
     * 
     * date:2017年6月20日
     * author: EK_熊
     */
    private function _check_leader(){
        $account = new AccountService();
        $month_pre_start = date("Y-m-d",mktime(0,0,0,date("m")-1,1,date("Y")));
        $account_map['leader_id']=$this->user_uid;
        $account_map['_string']="`status`=1 or (`status`=0 and `quit_date`>$month_pre_start)";
        $underling = $account->get_all_user_baseinfo('sn',$account_map);
        if (!$underling) return false;
        return true;
    }
    
    
    /**
     * 日历
     * 
     * date:2017年2月21日
     * author: EK_熊
     */
    public function calendar($pre='60',$next='60'){
        $startDay = date("Y-m-d",strtotime("-{$pre} day"));//前30天
        $timeStamp_start = strtotime($startDay);
        $endDay = date("Y-m-d",strtotime("+{$next} day"));//后30天
        $timeStamp_end = strtotime($endDay);
        $calendar = [];
        
        //获取法定节假日
        $festival = M('Festival')->where(['date'=>['between',[$startDay,$endDay]]])->getField('date,type,title',true);
        
        //获取个人考勤数据
        $attMap['sn'] = $this->user_sn;
        $attMap['date'] = ['between',[$startDay,$endDay]];
        
        $leaveType = implode(',',(C('VACATION_TYPE_EN')));
        $field = "DATE_FORMAT(duty_on,'%H:%i:%s') as duty_on,DATE_FORMAT(duty_off,'%H:%i:%s') as duty_off,
        work_actual,work_effect_918,work_effect,overtime,stu_absent,
        leave_evection,leave_long_distance,leave_evection,
        compensatory_consume,stu_late,stu_leave_early,{$leaveType}";
        $userData = D('AttendanceDay')->where($attMap)->getField("date as _date,$field",true);

        $applyMap['sn'] = $this->user_sn;
        $applyMap['start_time|end_time'] = ['between',[$startDay,$endDay]];
        $applyMap['status'] = ['in','0,1'];
        $waitApply = D('Apply')->where($applyMap)->field('DATE_FORMAT(start_time,"%Y-%m-%d") as start_time,DATE_FORMAT(end_time,"%Y-%m-%d") as end_time,type,status')->select();
        $totalDay = intval($pre)+intval($next)+1;
        for ($i=0;$i<$totalDay;$i++){
            $dateInfo = getdate($timeStamp_start);
            $date = date('Y-m-d',$timeStamp_start);
            $userAtten = [];
            $workMin = 480;
            
            if ($userData[$date] && ($date >= $this->userInfo['join_date'])){
                $userAtten['zan'] = 0;
                $leavetime = leave_mins_day($userData[$date]);
                foreach ($userData[$date] as $k=> $v){
                    $userAtten[$k] = $userData[$date][$k] ? $userData[$date][$k] : 0;
                }
//                 if ($leavetime>0){
//                     $leave_actu = $leavetime+intval($userData[$date]['work_actual']);
//                     $userAtten['work_actual'] = $leave_actu;
//                     if (($leave_actu < $workMin) && is_work_day($date)){
//                         $userAtten['stu_absent'] = $workMin-$leave_actu;//缺勤 = 480 - （实际出勤+外出）
//                     }else{
//                         $userAtten['stu_absent'] =0; 
//                     }
//                 }

                //哺乳期的缺勤时间计算 = 哺乳期应出勤时长-实际时长-请假时长
                if(isset($this->userInfo['suckling']) && $this->userInfo['suckling']['date_start'] <= $date && $this->userInfo['suckling']['date_end'] >= $date){
                    $userAtten['stu_absent'] = $this->userInfo['suckling']['total_min']-$userData[$date]['work_actual']-$leavetime;
                }
                
                //缺勤要减去请假时长
                $userAtten['stu_absent'] = $userAtten['stu_absent'] >0 ? $userAtten['stu_absent'] :0;
                //9:00前上班并且18:00后下班显示赞的标志
                if (strtotime($date.''.$userData[$date]['duty_on']) < strtotime("$date 09:00:00") && strtotime($date.''.$userData[$date]['duty_off']) > strtotime("$date 18:00:00")) {
                    $userAtten['zan'] = 1;
                } 
            }
            //旷工1 : 缺时时长-当天的全部请假分钟数 >= 180分钟，
            //旷工2 ： 无打卡，无即无记录，
            //旷工3 ： 9到18点上班分钟数 小于 300分钟，
            //注意：排除当月入职情况,排除非工作日
            if (is_work_day($date) && (CURRENT_TIME > $date.' 23:59:59') && ($date > $this->userInfo['join_date'])) {
                if (empty($userAtten) || (($userData[$date]['work_effect_918'] + $leavetime<=300))) {
                    $userAtten['stu_kuanggong'] = true;
                }
            }
            
            
            
            if ($date == date('Y-m-d')) {
                $userAtten['stu_late'] = 0;
                $userAtten['stu_leave_early'] = 0;
            }
            $apply_wait = 0;//是否有待审核的申请
            $apply_4_succ = 0;//补打卡是否有待审核的申请
            foreach ($waitApply as $wv){

                //检查当天日期的是否有待审核申请数据
                if ($wv['start_time'] && $wv['end_time'] && $date>=$wv['start_time'] && $date <= $wv['end_time']) {
                    if ($wv['status'] == 0) {
                        $apply_wait = 1;
                    }
                }
                if ($wv['type']==4 && ($date==$wv['start_time'] || $date == $wv['end_time'])) {
                   if ($wv['status'] == 0){
                       $apply_wait = 1;
                   }else{
                       $apply_4_succ = 1;
                   }
                }
                
            }
//             $all_leave_min = leave_mins_day_except($userAtten,'leave_casual');
            $calendar[$dateInfo['year']][$dateInfo['mon']][] = [
                'day'=>$dateInfo['mday'],
                'week'=>$dateInfo['wday'],
                'month'=>$dateInfo['mon'],
                'year'=>$dateInfo['year'],
                'festival'=>$festival[$date] ? $festival[$date] : [],
                'attendance'=>$userAtten,
                'apply_wait'=>$apply_wait,//申请,待审核状态
                'apply_4_succ'=>$apply_4_succ,//补打卡是否通过
            ];
                
            $timeStamp_start = $timeStamp_start+86400;
        }
        $today = getdate();
        $data['today'] =[
            'day'=>$today['mday'],
            'week'=>$today['wday'],
            'month'=>$today['mon'],
            'year'=>$today['year'],
        ]; 

        $data['calendar'] = $calendar;
        $data['status'] = 'success';
        $this->ajaxReturn($data);
    }
    
    //模拟打卡
    public function simulate(){
        $clocktime = I('time');
        $dev_code = I('dev_code');
        
        if (IS_POST) {
            $tmp = range(1,30);
            $numstr = M('Attendance')->where(['dev_code'=>['like',"%$dev_code%"]])->order('dev_id desc')->getField('dev_id');
            $clocktime = I('time').':00';
            $data[] = [
                'dev_id'=>$numstr,
                'name'=>$this->userInfo['name'],
                'sn'=>$this->user_sn,
                'time'=>$clocktime,
                'dev_code'=>'fzzx_1'
            ];
            $ret = R('Loader/attendance',[$data,false]);
            
            if($ret['errcode'] == 0) $this->success($ret['errmsg']);
            $this->error($ret['errmsg']);
        }
        $this->display();
    }
    
}